﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Tsanie.DmPoster {
    public partial class SelectForm : Form {
        internal static Dictionary<string, string> users = new Dictionary<string, string>();
        private DialogResult _result = DialogResult.Cancel;
        public List<string> Selected { get; set; }

        static SelectForm() {
            try {
                StreamReader reader = new StreamReader("users.txt");
                users.Clear();
                string line;
                while ((line = reader.ReadLine()) != null) {
                    string[] pars = line.Split(',');
                    if (pars.Length >= 2) {
                        users.Add(pars[0], pars[1]);
                    }
                }
            } catch { }
        }

        public static DialogResult ShowDialog(Form owner, IEnumerable<string> selected,
            out List<string> result) {
            SelectForm frm = new SelectForm();
            foreach (string str in selected) {
                if (users.ContainsKey(str)) {
                    ListViewItem lvi = frm.listSelect.Items.Add(str);
                    lvi.SubItems.Add(users[str]);
                } else {
                    frm.listSelect.Items.Add(str);
                }
            }
            frm.ShowDialog(owner);
            result = frm.Selected;
            return frm._result;
        }

        private SelectForm() {
            InitializeComponent();
        }
        private void SelectForm_Load(object sender, EventArgs e) {
            if (Owner != null) {
                this.Top = Owner.Top + 20;
                this.Left = Owner.Left + 20;
            }
        }
        private void buttonCancel_Click(object sender, EventArgs e) {
            this.Close();
        }
        private void buttonOk_Click(object sender, EventArgs e) {
            _result = System.Windows.Forms.DialogResult.OK;
            int count = listSelect.SelectedIndices.Count;
            bool filter = radioFilter.Checked;
            if (filter)
                count = listSelect.Items.Count - count;
            Selected = new List<string>();
            for (int i = 0; i < listSelect.Items.Count; i++) {
                ListViewItem item = listSelect.Items[i];
                bool check = item.Checked;
                if ((check && !filter) || (!check && filter)) {
                    Selected.Add(item.Text);
                }
            }
            this.Close();
        }
    }
}
